package com.hengxinguotong.zhihuichengjian.ui.engineering.reservation;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TimePicker;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.Reservation;
import com.hengxinguotong.zhihuichengjian.bean.ReservationListRes;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.bean.UserInfo;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchPersonActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.StructureActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectListPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**新增预约
 * Created by Administrator on 2017/4/1.
 */

public class AddReservationActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_tv)
    HXTextView saveTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.urgent_tv)
    HXTextView urgentTv;
    @BindView(R.id.urgent_checkbox)
    CheckBox urgentCheckbox;
    @BindView(R.id.switch_bt)
    Switch switchBt;
    @BindView(R.id.structure_tv)
    HXTextView structureTv;
    @BindView(R.id.position_rl)
    RelativeLayout positionRl;
    @BindView(R.id.reservation_device_tv)
    HXTextView reservationDeviceTv;
    @BindView(R.id.profession_rl)
    RelativeLayout professionRl;
    @BindView(R.id.reservation_time_tv)
    HXTextView reservationTimeTv;
    @BindView(R.id.handle_person_tv)
    HXTextView handlePersonTv;
    @BindView(R.id.description_etv)
    HXEditTextView descriptionEtv;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.team_tv)
    HXTextView teamTv;
    @BindView(R.id.username_tv)
    HXTextView usernameTv;
    @BindView(R.id.usermobile_tv)
    HXTextView usermobileTv;
    @BindView(R.id.histroy_ll)
    LinearLayout histroyLl;
    @BindView(R.id.main_sv)
    ScrollView mainSv;
    @BindView(R.id.result_tv)
    HXTextView resultTv;
    @BindView(R.id.pass)
    RadioButton pass;
    @BindView(R.id.notpass)
    RadioButton notpass;
    @BindView(R.id.result_rg)
    RadioGroup resultRg;
    @BindView(R.id.result_ll)
    LinearLayout resultLl;
    @BindView(R.id.title_tv)
    HXTextView title_tv;
    private Structure structure;
    private SelectListPop mSelectListPop;
    private int deviceSelectPosition = -1;
    private Company mCompany;
    private Reservation reservation;
    public static final String[] devices = {"塔吊", "升降机"};
    private ViewHolder viewHolder;
    private boolean isOnlyRead = false;
    private String handlePersonId; //处理人id
    private String handlePersonName; //处理人
    private int workType;
    private UserInfo userInfo;
    private final int SELECTPERSON = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addreservation);
        ButterKnife.bind(this);
        deviceSelectPosition = getIntent().getIntExtra("equipmentType", 1) - 1;
        if(deviceSelectPosition == 0){
            workType = Constants.workTypeHashMap.get("司索工");//塔吊即司索工
            title_tv.setText("塔吊预约");
        }else{
            workType = Constants.workTypeHashMap.get("升降机司机");
            title_tv.setText("升降机预约");
        }
        reservationDeviceTv.setText(devices[deviceSelectPosition]);
        reservation = (Reservation) getIntent().getSerializableExtra("reservation");
        isOnlyRead = getIntent().getBooleanExtra("isOnlyRead", false);
        if (reservation == null) {
            String json = SPUtil.getString(AddReservationActivity.this, "json");
            reservationTimeTv.setText(Utils.geNowTime());
            userInfo = new Gson().fromJson(json, UserInfo.class);
            if(userInfo.getValue() != null){
                usernameTv.setText(userInfo.value.getRealName());
                if(userInfo.getValue().getPerson() != null){
                    if(userInfo.getValue().getPerson().getProjectCompanyName() != null){
                        companyTv.setText(userInfo.value.getPerson().getProjectCompanyName());
                    }
                    if(userInfo.getValue().getPerson().getTeamName() != null){
                        teamTv.setText(userInfo.value.getPerson().getTeamName());
                    }
                    if(userInfo.getValue().getPerson().getMobile() != null){
                        usermobileTv.setText(userInfo.value.getPerson().getMobile());
                    }
                }
            }
        } else {
            if ("1".equals(reservation.getStatus())) {
                if (hasSubmit()) {
                    saveTv.setText("开始处理");
                } else {
                    saveTv.setVisibility(View.GONE);
                }
            } else if ("2".equals(reservation.getStatus())) {
                if (hasAudit()) {
                    saveTv.setText("提交");
                    resultTv.setVisibility(View.VISIBLE);
                    resultLl.setVisibility(View.VISIBLE);
                } else {
                    saveTv.setVisibility(View.GONE);
                }
            } else if ("3".equals(reservation.getStatus())) {
                if (hasSubmit()) {
                    saveTv.setText("确认完成");
                } else {
                    saveTv.setVisibility(View.GONE);
                }
            } else if ("4".equals(reservation.getStatus())) {
                saveTv.setVisibility(View.GONE);
            } else if ("5".equals(reservation.getStatus())) {
                saveTv.setVisibility(View.GONE);
            }
            if (isOnlyRead) {
                saveTv.setVisibility(View.GONE);
                resultLl.setVisibility(View.GONE);
                resultTv.setVisibility(View.GONE);
            }
            deviceSelectPosition = reservation.getEquipmentType() - 1;
            switchBt.setEnabled(false);
            switchBt.setChecked(reservation.getIsUrgentTask() == 1);
            Utils.setEditTextViewUnable(reservation.getScheduledPlanName(), structureTv);
            Utils.setEditTextViewUnable(devices[deviceSelectPosition], reservationDeviceTv);
            Utils.setEditTextViewUnable(reservation.getScheduledPlanName(), structureTv);
            Utils.setEditTextViewUnable(reservation.getRemark(), descriptionEtv);
            Utils.setEditTextViewUnable(reservation.getAppointmentDate(), reservationTimeTv);
            Utils.setEditTextViewUnable(reservation.getHandleName(), handlePersonTv);

            companyTv.setText(reservation.getProjectCompanyName());
            teamTv.setText(reservation.getTeamName());
            usernameTv.setText(reservation.getAppointmentName());
            usermobileTv.setText(reservation.getMobile());
            getHistoryInfo();
        }
    }

    @OnClick({R.id.iv_back, R.id.save_tv, R.id.structure_tv, R.id.reservation_device_tv, R.id.reservation_time_tv, R.id.handle_person_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_tv:
                if (reservation == null) {
                    addReservation();
                } else {
                    if ("1".equals(reservation.getStatus())) {
                        updateState("3");
                    } else if ("2".equals(reservation.getStatus())) {
                        if (resultRg.getCheckedRadioButtonId() == R.id.pass) {
                            updateState("1");
                        } else if (resultRg.getCheckedRadioButtonId() == R.id.notpass) {
                            updateState("4");
                        } else {
                            showToast("请选择审核结果");
                        }
                    } else if ("3".equals(reservation.getStatus())) {
                        updateState("5");
                    }
                }
                break;
            case R.id.structure_tv:
                StructureActivity.FROM = 2;
                intent = new Intent(this, StructureActivity.class);
                startActivity(intent);
                break;
            case R.id.reservation_device_tv:
                showSelectPop();
                break;
            case R.id.reservation_time_tv:
                showDatePickerDialog();
                break;
            case R.id.handle_person_tv:
                intent = new Intent(this, PersonLiableListActivity.class);
                intent.putExtra("type", 1);
                startActivityForResult(intent, SELECTPERSON);
                break;
        }
    }


    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        structure = (Structure) intent.getSerializableExtra("struct");
        if (structure != null) {
            structureTv.setText(structure.getName());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECTPERSON && data != null) {
            User user = (User) data.getSerializableExtra("selectUser");
            handlePersonId = user.getUserId();
            handlePersonName = user.getName();
            handlePersonTv.setText(handlePersonName);
        }
    }

    private void showSelectPop() {
        mSelectListPop = new SelectListPop(this, R.layout.dialog_select_sex, devices, new SelectListPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                deviceSelectPosition = position;
                reservationDeviceTv.setText(devices[position]);
            }
        });
        mSelectListPop.setFocusable(true);
        mSelectListPop.setOutsideTouchable(true);
        mSelectListPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectListPop.update();
        mSelectListPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectListPop.isShowing()) {
            mSelectListPop.dismiss();
        } else {
            mSelectListPop.showAtLocation(mainSv, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        }
    }


    private void showDatePickerDialog() {
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        showTimePickerDialog(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
    }

    private void getHistoryInfo() {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("taskAppointmentId", reservation.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/taskAppointment/queryListDetial/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    ReservationListRes reservationListRes = gson.fromJson(json, ReservationListRes.class);
                    for (Reservation _Reservation :
                            reservationListRes.getValue()) {
                        View convertView = LayoutInflater.from(AddReservationActivity.this)
                                .inflate(R.layout.item_reservation_task, null, false);
                        viewHolder = new ViewHolder(convertView);
                        viewHolder.data.setText(_Reservation.getCreateTime());
                        viewHolder.name.setText(_Reservation.getAppointmentName());
                        if ("1".equals(_Reservation.getTaskStatus())) {
                            if (reservation.getIsUrgentTask() == 1) {
                                viewHolder.stateTv.setText("审核通过");
                            } else {
                                viewHolder.stateTv.setText("新增预约");
                            }
                            viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                            viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                        } else if ("2".equals(_Reservation.getTaskStatus())) {
                            viewHolder.stateTv.setText("新增紧急预约");
                            viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                            viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                        } else if ("3".equals(_Reservation.getTaskStatus())) {
                            viewHolder.stateTv.setText("开始处理");
                            viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                            viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                        } else if ("4".equals(_Reservation.getTaskStatus())) {
                            viewHolder.stateTv.setText("审核不通过");
                            viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_f1636a));
                            viewHolder.stateIv.setImageResource(R.mipmap.canceled);
                        } else {
                            viewHolder.stateTv.setText("处理完成");
                            viewHolder.stateTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                            viewHolder.stateIv.setImageResource(R.mipmap.already_confirmed);
                        }
                        histroyLl.addView(convertView);
                    }
                    histroyLl.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    class ViewHolder {
        @BindView(R.id.state_iv)
        ImageView stateIv;
        @BindView(R.id.state_tv)
        HXTextView stateTv;
        @BindView(R.id.name)
        HXTextView name;
        @BindView(R.id.data)
        HXTextView data;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    private boolean checkContent() {
        if (userInfo == null) {
            showToast("个人信息有误，请重新登录");
            return false;
        }

//        if (structure == null) {
//            showToast("请选择工程结构");
//            return false;
//        }

        if (Utils.isEmpty(reservationTimeTv.getText() + "")) {
            showToast("请选择预约时间");
            return false;
        }

        if(Utils.isEmpty(handlePersonId)){
            showToast("请选择处理人");
            return false;
        }

        return true;
    }

    private void addReservation() {
        if (!checkContent()) {
            return;
        }

        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        if(null != structure){
            params.addBodyParameter("projectStructureId", structure.getId());
        }
        params.addBodyParameter("isUrgentTask", switchBt.isChecked() ? "1" : "0");
        params.addBodyParameter("equipmentType", (deviceSelectPosition + 1) + "");
        params.addBodyParameter("projectCompanyId", userInfo.value.getPerson().getProjectCompanyId());
        params.addBodyParameter("appointmentDate", reservationTimeTv.getText() + "");
        params.addBodyParameter("appointmentId", SPUtil.getString(this, "userId"));
        params.addBodyParameter("handlePerson", handlePersonId);

        if (!Utils.isEmpty(userInfo.value.getPerson().getTeamId())) {
            params.addBodyParameter("teamId", userInfo.value.getPerson().getTeamId());
        }
        params.addBodyParameter("remark", descriptionEtv.getEditableText().toString());
        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));


        Utils.requestData(getResources().getString(R.string.loading), AddReservationActivity.this, "/taskAppointment/insertTaskAppointmnet/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    AddReservationActivity.this.showToast("预约成功");
                    setResult(1);
                    finish();
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
//                    String status = object.getString("status");
//                    String msg = object.getString("msg");
//                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void updateState(String state) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("taskAppointmentId", reservation.getId());
        params.addBodyParameter("taskStatus", state);
        params.addBodyParameter("appointmentId", SPUtil.getString(this, "userId"));


        Utils.requestData(getResources().getString(R.string.loading), AddReservationActivity.this, "/taskAppointment/insertTaskAppointmnetProcess/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    showToast("提交成功");
                    setResult(1);
                    finish();
                }
            }

            @Override
            public void onFailure(String json) {
                showToast("提交失败");
            }
        });
    }


    private void showTimePickerDialog(final String date) {
        Calendar c = Calendar.getInstance();
        new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                reservationTimeTv.setText(date + " " + hourOfDay + ":" + minute);

            }
        }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true).show();
    }
}
